<template>

  <a-modal :visible="show" title="用户组角色" width="800px" :footer="false" @cancel="closeIt">

    <a-table v-model:selectedKeys="selectedKeys" row-key="roleId" :columns="columns" :data="renderData"
      :bordered="false" :size="'medium'" :row-selection="rowSelection" @select="rowSelect">
    </a-table>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, computed } from 'vue';
import type { TableColumnData, TableData } from '@arco-design/web-vue/es/table/interface';
import { getAppRoles } from '@/api/dashboard/apps';
import { getGroupRoles, bindRole, unbindRole } from '@/api/dashboard/usergroup';
import { Message } from '@arco-design/web-vue';

const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: false,
  checkStrictly: false
});

const columns = computed<TableColumnData[]>(() => [
  {
    title: '编号',
    dataIndex: 'roleId',
    width: 90,
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    width: 120,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    ellipsis: true,
    tooltip: true,
  },
]);

const renderData = ref<TableData[]>();

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  appid: {
    type: Number,
    default: 0
  },
  groupid: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['close']);
function closeIt() {
  emit('close');
}

const selectedKeys = ref([]);
function rowSelect(rowKeys: Array<number>, key: number, record: any) {
  if (rowKeys.includes(key)) {
    bindRole(gid, key);
    Message.success('分配角色成功。');
  } else {
    unbindRole(gid, key);
    Message.success('解除角色成功。');
  }
}

async function getAll() {
  let data = await getAppRoles(props.appid);
  renderData.value = data.items;
}

async function getRoles() {
  let data = await getGroupRoles(props.groupid);
  selectedKeys.value = data.map((a: any) => a.roleId);
}

let aid = 0, gid = 0;
watch(props, async (newp, oldp) => {
  if (aid !== newp.appid) {
    await getAll();
  }
  if (gid !== newp.groupid) {
    await getRoles();
  }
  aid = newp.appid;
  gid = newp.groupid;
});

</script>
